package com.alibaba.citrus.ots.sales.plan.functions.contract;

import com.alibaba.citrus.ots.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.ots.sales.plan.model.enums.ContractDataSourceEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.ContractStatDimensionEnum;
import com.alibaba.citrus.ots.sales.plan.repository.ContractRepository;
import com.alibaba.citrus.ots.sales.plan.repository.request.SearchContractRepoReq;
import com.alibaba.citrus.ots.sales.plan.sdo.ContractSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.common.util.set.Sets;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangyibing
 */
@Component
public class ContractAbility {
    Log log = Log.getLogger(ContractAbility.class);

    @Resource
    private ContractRepository contractRepository;

    public Integer batchCreateContract(List<ContractSDO> createContractRequestList) {
        if (CollectionUtils.isEmpty(createContractRequestList)){
            return 0;
        }
        return contractRepository.batchCreateContract(createContractRequestList);
    }

    /**
     *  TODO 导入：先批量查询（类型，客户，客户地址，货品，合同年份），对比请求数据，different，得到批量插入，批量修改
     * @param createContractRequestList
     * @return
     */
    public Integer batchCreateContract(String type,List<ContractSDO> createContractRequestList) {
        if (CollectionUtils.isEmpty(createContractRequestList)) {
            return 0;
        }
        Set<String> contractYearList = Sets.newHashSet();
        Set<String> customerCodeList = Sets.newHashSet();
        Set<String> customerAddressList = Sets.newHashSet();
        Set<String> customerAddressIdList = Sets.newHashSet();
        Set<String> scItemIdList = Sets.newHashSet();
        Set<String> orgBusinessUnitCodeList = Sets.newHashSet();
        Set<String> orgSalesOrganizationCodeList = Sets.newHashSet();
        Set<String> orgSalesChannelCodeList = Sets.newHashSet();
        Set<String> orgSalesDepartmentCodeList = Sets.newHashSet();
        createContractRequestList.forEach(contract -> {
            if (!Objects.isNull(contract.getContractYear())) {
                contractYearList.add(contract.getContractYear());
            }
            if (!Objects.isNull(contract.getCustomerCode())) {
                customerCodeList.add(contract.getCustomerCode());
            }
            if (!Objects.isNull(contract.getCustomerAddress())) {
                customerAddressList.add(contract.getCustomerAddress());
            }
            if (!Objects.isNull(contract.getCustomerAddressId())){
                customerAddressIdList.add(contract.getCustomerAddressId());
            }
            if (!Objects.isNull(contract.getScItemId())) {
                scItemIdList.add(contract.getScItemId());
            }
            if (!Objects.isNull(contract.getOrgBusinessUnitCode())) {
                orgBusinessUnitCodeList.add(contract.getOrgBusinessUnitCode());
            }
            if (!Objects.isNull(contract.getOrgSalesOrganizationCode())) {
                orgSalesOrganizationCodeList.add(contract.getOrgSalesOrganizationCode());
            }
            if (!Objects.isNull(contract.getOrgSalesChannelCode())) {
                orgSalesChannelCodeList.add(contract.getOrgSalesChannelCode());
            }
            if (!Objects.isNull(contract.getOrgSalesDepartmentCode())) {
                orgSalesDepartmentCodeList.add(contract.getOrgSalesDepartmentCode());
            }
        });

        SearchContractRepoReq searchContractRepoReq = new SearchContractRepoReq();
        searchContractRepoReq.setOrgBusinessUnitCodeList(Lists.newArrayList(orgBusinessUnitCodeList));
        if (type.equals(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode())) {
            searchContractRepoReq.setOrgSalesOrganizationCodeList(Lists.newArrayList(orgSalesOrganizationCodeList));
            searchContractRepoReq.setOrgSalesChannelCodeList(Lists.newArrayList(orgSalesChannelCodeList));
            searchContractRepoReq.setOrgSalesDepartmentCodeList(Lists.newArrayList(orgSalesDepartmentCodeList));
            searchContractRepoReq.setCustomerCodeList(Lists.newArrayList(customerCodeList));
            searchContractRepoReq.setCustomerAddressList(Lists.newArrayList(customerAddressList));
            searchContractRepoReq.setCustomerAddressIdList(Lists.newArrayList(customerAddressIdList));
            // 客户任务量导入
            searchContractRepoReq.setDataSourceList(Lists.newArrayList(ContractDataSourceEnum.EXCEL.getCode()));
        } else {
            // 公司任务量导入
            searchContractRepoReq.setDataSourceList(Lists.newArrayList(ContractDataSourceEnum.CRM.getCode()));
        }
        searchContractRepoReq.setTypeList(Lists.newArrayList(type));
        searchContractRepoReq.setContractYearList(Lists.newArrayList(contractYearList));
        searchContractRepoReq.setScItemIdList(Lists.newArrayList(scItemIdList));
//        searchContractRepoReq.setLimit(createContractRequestList.size());
        PageResult<List<ContractSDO>> listPageResult = contractRepository.pageQueryContract(searchContractRepoReq);
        List<ContractSDO> localContract = listPageResult.getContent();
        if (CollectionUtils.isEmpty(localContract)) {
            return contractRepository.batchCreateContract(createContractRequestList);
        }
        Map<String, ContractSDO> localCollect = localContract.stream().collect(Collectors.toMap(contract -> SalesPlanCommonService.getCombinationKey(contract.getContractYear(), contract.getCustomerCode(), contract.getCustomerAddress(),contract.getCustomerAddressId(), contract.getScItemId()), a -> a, (a, b) -> a));
        List<ContractSDO> addList = Lists.newArrayList();
        List<ContractSDO> updateList = Lists.newArrayList();
        for (ContractSDO contract : createContractRequestList) {
            ContractSDO contractSDO = localCollect.get(SalesPlanCommonService.getCombinationKey(contract.getContractYear(), contract.getCustomerCode(), contract.getCustomerAddress(),contract.getCustomerAddressId(), contract.getScItemId()));
            if (Objects.isNull(contractSDO)){
                addList.add(contract);
            }else {
                contract.setId(contractSDO.getId());
                contract.setGmt_modified(new Date());
                updateList.add(contract);
            }
        }
        if (CollectionUtils.isNotEmpty(addList)){
            contractRepository.batchCreateContract(createContractRequestList);
        }
        if (CollectionUtils.isNotEmpty(updateList)){
            updateList.forEach(contractSDO -> {
                try {
                    contractRepository.editContract(contractSDO);
                } catch (Exception e) {
                    log.info("ContractFileService.customerImportHandle.editContract=" + JSONObject.toJSONString(contractSDO));
                    log.info("ContractFileService.customerImportHandle.editContract:Exception=" + JSONObject.toJSONString(e));
                }
            });
        }
        return addList.size() + updateList.size();
    }
}
